<template>
  <div>
    <BlogList
      :loadData="loadData"
      :blogList="blogList"
      :totalPage="totalPage"
    />
  </div>
</template>

<script>
import BlogList from '@/components/blog/BlogList'
import { selectListByPage } from '@/api/blog'
import { SET_IS_BLOG_TO_HOME } from '../../store/mutations-types'

export default {
  name: 'Home',
  components: { BlogList },
  data() {
    return {
      blogList: [],
      totalPage: 0,
      getBlogListFinish: false,
      queryInfo: {
        page: {
          page: 1,
          limit: 3
        }
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.name !== 'blog') {
        //其它页面跳转到首页时，重新请求数据
        //设置一个flag，让首页的分页组件指向正确的页码
        vm.$store.commit(SET_IS_BLOG_TO_HOME, false)
        vm.loadData()
      } else {
        //如果文章页面是起始访问页，首页将是第一次进入，即缓存不存在，要请求数据
        if (!vm.getBlogListFinish) {
          vm.loadData()
        }
        //从文章页面跳转到首页时，使用首页缓存
        vm.$store.commit(SET_IS_BLOG_TO_HOME, true)
      }
    })
  },
  methods: {
    /**
     * 获取博客数据
     *
     * @param {*} pageNum 页数
     * @return {*}
     * @description:
     * @author: WangJin
     * @date: 2023-07-01 16:41:28
     */
    loadData(pageNum) {
      if (pageNum) {
        this.queryInfo.page.page = pageNum
      }
      const token = this.$store.getters.token
      this.queryInfo.adminToken = token
      selectListByPage(this.queryInfo).then(res => {
        this.blogList = res.data.rows
        this.totalPage = res.data.totalPage
        this.$nextTick(() => {
          Prism.highlightAll()
        })
        this.getBlogListFinish = true
      })
    }
  }
}
</script>

<style scoped></style>
